<?php

namespace common\models\c2\entity;

use common\models\c2\statics\AttributeInputType;
use common\models\c2\statics\WhetherType;
use Yii;
use yii\helpers\ArrayHelper;
use yii\validators\RequiredValidator;

/**
 * This is the model class for table "{{%attribute}}".
 *
 * @property string $id
 * @property integer $type
 * @property string $code
 * @property string $name
 * @property string $label
 * @property string $hint
 * @property string $input_type
 * @property string $default_value
 * @property string $memo
 * @property integer $is_sku
 * @property integer $is_visible
 * @property integer $is_required
 * @property integer $is_unique
 * @property integer $is_depend
 * @property string $depend_id
 * @property integer $status
 * @property integer $position
 * @property string $created_at
 * @property string $updated_at
 */
class Attribute extends \kzo\base\models\ActiveRecord
{
    public $items;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%attribute}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type', 'is_sku', 'is_visible', 'is_required', 'is_unique', 'is_depend', 'depend_id', 'status', 'position'], 'integer'],
            [['is_depend', 'depend_id'], 'default', 'value' => 0],
            [['code', 'label'], 'required'],
            [['default_value', 'memo'], 'string'],
            [['created_at', 'updated_at'], 'safe'],
            [['items',], 'validateItems'],
            [['code', 'name', 'label', 'hint', 'input_type'], 'string', 'max' => 255],
        ];
    }

    public function validateItems($attribute)
    {
        $requiredValidator = new RequiredValidator();

        foreach ($this->$attribute as $index => $row) {
            $error = null;
            $requiredValidator->validate($row['label'], $error);
            if (!empty($error)) {
                $key = $attribute . '[' . $index . '][label]';
                $this->addError($key, $error);
            }
            $requiredValidator->validate($row['value'], $error);
            if (!empty($error)) {
                $key = $attribute . '[' . $index . '][value]';
                $this->addError($key, $error);
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'type' => Yii::t('app.c2', 'Type'),
            'code' => Yii::t('app.c2', 'Code'),
            'name' => Yii::t('app.c2', 'Name'),
            'label' => Yii::t('app.c2', 'Label'),
            'hint' => Yii::t('app.c2', 'Hint'),
            'input_type' => Yii::t('app.c2', 'Input Type'),
            'default_value' => Yii::t('app.c2', 'Default Value'),
            'memo' => Yii::t('app.c2', 'Memo'),
            'is_sku' => Yii::t('app.c2', 'Is Sku'),
            'is_visible' => Yii::t('app.c2', 'Is Visible'),
            'is_required' => Yii::t('app.c2', 'Is Required'),
            'is_unique' => Yii::t('app.c2', 'Is Unique'),
            'is_depend' => Yii::t('app.c2', 'Is Depend'),
            'depend_id' => Yii::t('app.c2', 'Depend ID'),
            'status' => Yii::t('app.c2', 'Status'),
            'position' => Yii::t('app.c2', 'Position'),
            'created_at' => Yii::t('app.c2', 'Created At'),
            'updated_at' => Yii::t('app.c2', 'Updated At'),
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\AttributeQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\AttributeQuery(get_called_class());
    }

    /**
     * setup default values
     **/
    public function loadDefaultValues($skipIfSet = true)
    {
        parent::loadDefaultValues($skipIfSet);
        if ($this->isNewRecord) {
            $this->is_sku = 1;
        }
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
        if (AttributeInputType::isMultiple($this->input_type)) {
            if (!empty($this->items)) {
                foreach ($this->items as $item) {
                    $attributes = [
                        'code' => isset($item['code']) ? $item['code'] : "",
                        'name' => isset($item['name']) ? $item['name'] : "",
                        'label' => isset($item['label']) ? $item['label'] : "",
                        'value' => isset($item['value']) ? $item['value'] : "",
                        'is_selected' => isset($item['is_selected']) ? $item['is_selected'] : 0,
                        'position' => isset($item['position']) ? $item['position'] : 50,
                    ];
                    if (isset($item['id']) && $item['id'] == 0) {  // create new items
                        $itemModel = new AttributeItem();
                        $itemModel->setAttributes($attributes);
                        $itemModel->link('owner', $this);
                    } elseif (isset($item['id'])) {  // update itemes
                        $itemModel = AttributeItem::findOne(['id' => $item['id']]);
                        if (!is_null($itemModel)) {
                            $itemModel->updateAttributes($attributes);
                        }
                    }
                }
            }
        }
    }

    public function loadItems()
    {
        $this->items = $this->getAttributeItems()->all();
    }

    public function getAttributeItems()
    {
        return $this->hasMany(AttributeItem::className(), ['attribute_id' => 'id'])
            ->orderBy(['position' => SORT_DESC]);
    }

    public function isMultiple()
    {
        return AttributeInputType::isMultiple($this->input_type);
    }

    public function getItemsHashMap($keyField, $valField, $condition = '')
    {
        return ArrayHelper::map(
            $this->getAttributeItems()
                ->select([$keyField, $valField])
                ->andWhere($condition)
                ->orderBy(['position' => SORT_DESC, 'id' => SORT_ASC])
                ->asArray()
                ->all(), $keyField, $valField);
    }

    public function getEavDefaultValue()
    {
        switch ($this->input_type) {
            case AttributeInputType::INPUT_RADIO_LIST:
            case AttributeInputType::INPUT_DROPDOWN_LIST:
                return implode(',',
                    $this->getAttributeItems()
                    ->select(['id'])
                    ->andWhere(['is_selected' => WhetherType::TYPE_YES])
                    ->column()
                );
                break;
            case AttributeInputType::INPUT_CHECKBOX_LIST:
                return $this->getAttributeItems()
                    ->select(['id'])
                    ->andWhere(['is_selected' => WhetherType::TYPE_YES])
                    ->column();
                break;
            case AttributeInputType::INPUT_RICHTEXT:
            case AttributeInputType::INPUT_TEXT:
            case AttributeInputType::INPUT_TEXTAREA:
            default:
                return $this->default_value;
        }
    }

    public function getTitle() {
        return !empty($this->label) ? $this->label : $this->name;
    }

    public function beforeDelete() {
        foreach ($this->attributeItems as $item) {
            $item->delete();
        }
        return parent::beforeDelete();
    }

    public function beforeSave($insert)
    {
        if (!$insert && ($this->code != $this->getOldAttribute('code'))) {
            ProductEav::updateAll(['attribute_code' => $this->code], ['attribute_id' => $this->id]);
        }
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

}
